<template>
  <div>
    <div style="padding: 10px 0">
      <el-input style="width: 200px" suffix-icon="el-icon-search" placeholder="请输入文件名称" v-model="name"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="padding: 10px 0">
      <el-upload action="http://localhost:9090/file/upload"
                 :on-success="handleFileUploadSuccess" :on-error="handleFileUploadError"
                 :show-file-list="false" style="display: inline-block" :limit=5>
        <el-button type="primary" class="ml-5"><i class="el-icon-upload2"></i> 上传文件</el-button>
      </el-upload>
      <el-button type="danger" class="ml-5" @click="isDelBatch"><i class="el-icon-delete"></i> 批量删除</el-button>
    </div>
    <el-table @selection-change="handleSelectionChange" :data="tableData" border stripe
              :cell-style="{'text-align':'center'}"
              :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="name" label="文件名称"></el-table-column>
      <el-table-column prop="type" label="文件类型"></el-table-column>
      <el-table-column prop="size" label="文件大小（KB）"></el-table-column>
      <el-table-column label="预览">
        <template slot-scope="scope">
          <el-avatar v-if="scope.row.type==='jpg'||scope.row.type==='png'||scope.row.type==='jpeg'"
                     :src="scope.row.url"></el-avatar>
          <el-button v-else type="primary" @click="preview(scope.row)"><i class="el-icon-view"></i> 预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="下载" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="download(scope.row.url)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ccc"
                     @change="changeEnable(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-popconfirm class="ml-5" title="确定要删除本条记录吗？"
                         cancel-button-text='我再想想' confirm-button-text='确定'
                         icon="el-icon-info" icon-color="red"
                         @confirm="deleteById(scope.row.id)">
            <el-button type="danger" slot="reference"><i class="el-icon-delete"></i>删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页插件-->
    <div class="pd-10">
      <el-pagination
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <!--批量删除弹框-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span><i class="el-icon-delete-solid" style="font-size: 35px"></i>  确定要删除这些文件吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delBatch">确 定</el-button>
        </span>
    </el-dialog>
    <!--视频预览-->
    <el-dialog title="视频预览" :visible.sync="dialogVisibleVideo" width="50%">
      <div>
        <div class='demo'>
          <video-player class="video-player-box"
                        ref="videoPlayer"
                        :playsinline="true"
                        :options="playerOptions"
                        @play="onPlayerPlay($event)"
                        @pause="onPlayerPause($event)"
                        @ended="onPlayerEnded($event)"
                        @waiting="onPlayerWaiting($event)"
                        @playing="onPlayerPlaying($event)"
                        @loadeddata="onPlayerLoadeddata($event)"
                        @timeupdate="onPlayerTimeupdate($event)"
                        @canplay="onPlayerCanplay($event)"
                        @canplaythrough="onPlayerCanplaythrough($event)"
                        @statechanged="playerStateChanged($event)"
                        @ready="playerReadied"></video-player>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {videoPlayer} from 'vue-video-player'
import 'video.js/dist/video-js.css'

export default {
  name: "File",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      type: "",
      size: 0,
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      dialogVisible: false,
      name: '',
      dialogVisibleVideo: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4", // 类型
          src: '' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      }
    }
  },
  components: {
    videoPlayer
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/file/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        }
      }).then(res => {
        this.total = res.data.total
        this.tableData = res.data.records
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    save() { //保存信息
      this.dialogFormVisible = false
      this.request.post("/file/save", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功！")
          this.dialogFormVisible = false
        } else {
          this.$message.error("保存失败，请重试！")
        }
        this.load()
      })
    },
    deleteById(id) { //根据id删除用户
      console.log("要删除的id:" + id)
      this.request.delete("/file/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功！")
          this.load()
        } else {
          this.$message.error("操作失败，请重试！")
        }
      })
    },
    handleSelectionChange(val) { //批量删除前的选择
      console.log(val) //val是一个数组对象，存放着每条记录的要展示的详细信息
      this.multipleSelection = val
    },
    isDelBatch() {
      this.dialogVisible = true
    },
    delBatch() { //批量删除
      let ids = this.multipleSelection.map(value => value.id) //从数组对象中获取到每一个的id项
      this.request.post("/file/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("批量删除成功！")
          this.load()
        } else {
          this.$message.error("操作失败，请重试！")
        }
        this.dialogVisible = false
      })
    },
    handleFileUploadSuccess() {
      this.$message.success("文件上传成功")
      this.load()
    },
    handleFileUploadError() {
      this.$message.error("操作异常，请重试")
    },
    download(url) {
      window.open(url);
    },
    changeEnable(row) {
      this.request.post("/file/changeEnable", row).then(res => {
        if (res.code === '200') {
          this.$message.success("操作成功")
          this.load()
        } else {
          this.$message.error("操作失败")
        }
      })
    },
    reset() {
      this.name = ""
    },
    preview(row) {
      if (row.type==='mp4'){
        this.dialogVisibleVideo = true
        this.playerOptions.sources[0].src = row.url
      }else {
        this.$message.error("此格式文件无法预览")
      }

    },
    // 播放回调
    onPlayerPlay(player) {
    },

    // 暂停回调
    onPlayerPause(player) {
    },

    // 视频播完回调
    onPlayerEnded($event) {
    },

    // DOM元素上的readyState更改导致播放停止
    onPlayerWaiting($event) {
    },

    // 已开始播放回调
    onPlayerPlaying($event) {
    },

    // 当播放器在当前播放位置下载数据时触发
    onPlayerLoadeddata($event) {
    },

    // 当前播放位置发生变化时触发。
    onPlayerTimeupdate($event) {
    },

    //媒体的readyState为HAVE_FUTURE_DATA或更高
    onPlayerCanplay(player) {
    },

    //媒体的readyState为HAVE_ENOUGH_DATA或更高。这意味着可以在不缓冲的情况下播放整个媒体文件。
    onPlayerCanplaythrough(player) {
    },

    //播放状态改变回调
    playerStateChanged(playerCurrentState) {
    },

    //将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。
    playerReadied(player) {
    }
  }
}
</script>

<style scoped>
</style>